<?php
require 'global.php';
// 不兼容游客, 待改进
if($customer_id==0) { header('Location:login.html?refer=order'); exit; }
$arr_i=$customer->get_row($customer_id);
$email=$arr_i['email']; // 发电邮用email

// 实例化类 init calsses
$sales_order=new DB(Tsales_order,$conn);
$sales_order_detail=new DB(Tsales_order_detail,$conn);
$address_book=new DB(Taddress_book,$conn);

// 电邮相关 email
include(ROOT."common/mail_send.php");
$email_template=new DB(Temail_template,$conn);

// cart 购物车数据
$cart=get_cart();
if(! $cart_qty) { header('location:./'); exit; }
//pre($cart); exit;

// order code
$ref_no=date('YmdHis').rand(1000,9999);

// save ref_no in cookie for Paypal, 保存订单号到cookie, Paypal 会用到
setcookie('ref_no',encrypt($ref_no),time()+3600);
$order=$_POST;

// 验证数据来源是否合法
$ver=$order['key'];
if($ver != md5('ecomgear'.date('Ymd'))){ yell('请勿非法提交数据, 谢谢.','./'); exit; }

// 是否使用积分/优惠券
$with_point=$order['with_point'];
$with_coupon=$order['with_coupon'];

// 订单数组 order
$arr=array(
    'currency_id'=>$order['currency_id'],
    'total_price'=>$order['total_price'],
    'order_price'=>$order['order_price'],
    'ref_no'=>$ref_no,
    'customer_id'=>$order['customer_id'],
    'email'=>$order['email'],
    'customer_remark'=>$order['customer_remark'],
    'invoice_header'=>$order['invoice_header'],
//	'payment_method_id'=>$order['payment_method'],
    'shipment_cost'=>$order['shipment_cost'],
    'is_virtual'=>$order['is_virtual'],
    'with_tax'=>$order['with_tax'],
    //'with_deposit'=>$order['with_deposit'],
    'tax'=>$order['tax'],
    'coupon_discount_amount'=>$order['discount_amount'],
    'fullcut_amount' => $order['fullcut_amount']
);

// coupon 
if($with_coupon){
    $coupon_id=$coupon->get_id('code',$order['coupon']);
    $arr['coupon_id']=$coupon_id;
}

// point 积分兑换 
if($with_point){
    $arr['point_id']=$order['point']; // 此处把point_id字段当做使用的积分数量来用
    $arr['point_discount_amount']=$order['point_amount'];
    if($order['total_price']==0) $arr['order_status']=2; // 完全用积分支付 pay off by point
}

// 获取详细送货数据, get address book detail
$address_id=$order['address_book_id'];
if($address_id > 0) $arr_address=$address_book->get_row($address_id);
// 收货信息 receiver info
if($address_id > 0){
    $arr['country']=$arr_address['country_id'];
    $arr['province']=$arr_address['province_id'];
    $arr['city']=$arr_address['city_id'];
    $arr['county']=$arr_address['county_id'];
    $arr['address']=$arr_address['street'];
    $arr['zip']=$arr_address['zip'];
    $arr['contact_name']=$arr_address['contact_name'];
    $arr['mobile']=$arr_address['mobile'];
    $arr['phone']=$arr_address['phone'];
    $arr['shipment_method_id']=$order['shipment_method'];
}
else { // 订单全为虚拟商品, 联系信息取自客户资料
    $arr_i=$customer->get_row($order['customer_id']);
    $arr['contact_name']=$arr_i['first_name'].' '.$arr_i['last_name'];
    $arr['mobile']=$arr_i['mobile'];
    $arr['phone']=$arr_i['phone'];
}
//pre($arr); exit;

// 把订单写入数据库, 此处代码为事务
// 货币 currency
$tem_currency_code=$arrcurrency[$order['currency_id']]['code'];

try {
    $db->begin_transaction();
    $sales_order->insert($arr);
    $order_id=$sales_order->get_last_insert_id();

    // 获取产品价格
    $arr_product=array();
    $in_array=array();
    foreach($cart as $val) $in_array[]=$val['pid'];
    $where=array();
    $where[]=array('name'=>'id','val'=>$in_array,'opn'=>'in');
    $tem=$product->get_rows_advanced(1024,$where);
    foreach($tem as $val) $arr_product[$val['id']]=$val;

    $in_array=array();
    foreach($cart as $val) $in_array[]=$val['var'];

    // variation 子产品
    $where=array();
    $arr_var=array();
    $where[]=array('name'=>'id','val'=>$in_array,'opn'=>'in');
    $tem=$product_variation->get_rows_advanced(1024,$where);
    foreach($tem as $val) $arr_var[$val['id']]=$val;

    // 写入订单详情, 此处未保存产品价格和折扣信息, 未完待续...
    foreach ($cart as $key => $val){
        $tem_product=$arr_product[$val['pid']];
        $tem_stock=$tem_product['stock'];
        $has_stock=$tem_stock>=$val['qty']?1:0;
        //$unit_price=round($tem_product['price']*$currency_rate,2);
        $unit_price=price($tem_product);
        if($val['var']>0){
            $tem_stock=$arr_var[$val['var']]['stock'];
            $has_stock=$tem_stock>=$val['qty']?1:0;
            //$unit_price=round($arr_var[$val['var']]['price']*$currency_rate,2);
            $unit_price=price($arr_var[$val['var']],1);
        }
        if($has_stock){
            $arr2=array(
                'sales_order_id'=>$order_id,
                'product_id'=>$val['pid'],
                'product_variation_id'=>$val['var'],
                'quantity'=>$val['qty'],
                'unit_price'=>$unit_price,
            );
            // 写入订单详情
            $sales_order_detail->insert($arr2);
        }
    }
    $db->commit();
}
catch(PDOException $ex) {
    //Something went wrong rollback!
    $db->rollBack();
    //yell(WEB_ORDER_SUBMIT_FAIL,'./cart.html'); exit;
    echo $ex->getMessage();
    exit;
}

// 减库存 reduce stock
$product->reduce_stock_by_order($ref_no);
// 加销量 add sold quantity
$product->add_sold_quantity_by_order($ref_no);

// 一切正常, 清空购物车
cart_clear();

// 登记优惠券消费情况 update coupon
if($with_coupon){
    $arr_coupon=array(
        'customer_id'=>$order['customer_id'],
        'is_used'=>1,
        'used_time'=>date('Y-m-d H:i:s'),
    );
    $coupon->update($arr_coupon,'id',$coupon_id);
}
// 登记积分消费情况 update point
if($with_point){
    $customer->reduce('usable_point',$order['point'],'id',$order['customer_id']);
}

// 是否全部为虚拟商品, 虚拟商品不需要配送, 且不需要收货地址
$are_virtual=1;

//钱包余额
$customer_info = $customer->get_row(decrypt($_COOKIE['customer_id']));

// payment method 支付方式
$arr_payment=array();
$tem=$payment_method->get_rows(32,'is_enabled',1,'seq_no');
foreach ($tem as $val){
    $arr_payment[$val['id']]=$val;
}
if(!$order['is_virtual']){
    $are_virtual=0;
}
// 根据货币 取消不支持的支付方式
// cny 人民币, paypal 不支持
if($currency_id==2) { if(isset($arr_payment[3])) unset($arr_payment[3]); }
// 非人民币, 支付宝/财付通/银联在线不支持
else {
    if(isset($arr_payment[1])) unset($arr_payment[1]);
    if(isset($arr_payment[2])) unset($arr_payment[2]);
    if(isset($arr_payment[4])) unset($arr_payment[4]);
}
if($are_virtual) unset($arr_payment[5]); // 如果全部为虚拟商品, 不能使用货到付款方式

// 风险控制 risk control for gindart
// if(($cart_order_price/$currency_rate)>=10) {
//     //remove low asp paypal
//     unset($arr_payment[7]);
// }
// else {
//     //remove high asp paypal
//     unset($arr_payment[3]);
// }

// 当前购物车内商品数量 cart qty
$cart=null;
$cart_qty=0;

// 发电邮 send email
// 邮件变量 email variables
$str_order=order2html($ref_no);
$var_email=array(
    '%nickname%'=>$customer_nickname,
    '%date%'=>date('Y-m-d'),
    '%datetime%'=>date('Y-m-d H:i:s'),
    '%url%'=>$baseurl,
    '%company%'=>$config['SITE_COMPANY_'.LANG],
    '%order%'=>$str_order,
    '%order_ref_no%'=>$ref_no,
);
// replace vars 替换变量
$arr_email = $email_template->get_row(3); // id=3 客户邮件

$subject=$arr_email['subject_'.$lang];
$body=$arr_email['content_'.$lang];
foreach ($var_email as $key => $value){
    $subject=str_replace($key, $value, $subject);
    $body=str_replace($key, $value, $body);
}
// 替换后台上传的无网址路径图片
$body=str_replace('/upload/', $baseurl.'upload/', $body);
$body='<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'.$subject.'</title></head><body>'.$body.'</body></html>';
$tem_array=explode(',', DAILY_SALES_ORDER_RECIPIENT_EMAILS);
$bcc=array();
foreach($tem_array as $val) $bcc[]=trim($val);
$arr_mail=array(
    'to'=>array($order['email']),
    'bcc'=>$bcc,
    'subject'=>$subject,
    'body'=>$body,
    'host'=>EMAIL_HOST,
    'account'=>EMAIL_ACCOUNT,
    'password'=>EMAIL_PASSWORD,
    'port'=>EMAIL_PORT,
    'name'=>EMAIL_NAME,
    'ssl'=>EMAIL_SSL,
);

// 发信给顾客并密送管理员 send email to customer, and bcc admin
if($gear)mail_send($arr_mail);
// email end

// 只用积分就付完了钱 payoff by point 
if($order['total_price']==0){
    $message=array(
    'tip'=>WEB_ORDER_ONLINE_PAID_SUCCESS,
    'links'=>array(array('name'=>WEB_MY_ORDER,'url'=>'myorder.html'),array('name'=>WEB_BACK_HOME,'url'=>'./')),
    'time'=>6.2,
    'url'=>'myorder.html',
    );
    require VIEW.'message.php';
    exit;
}

// SEO 设置 seo tags
$title=WEB_ORDER_SUBMIT.' - '.$config['SITE_COMPANY_'.LANG];
$kwd=$title;
$dpn=$kwd;

// view 加载视图
require VIEW.'payment.php';

// end of file